
import htmlStr from './htmlStr'
import painterStr from './painterStr'
export function downloadFile(url) {
	if(!url) return Promise.reject({err: 'no url'})
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

export function useNvue(path) {
	return new Promise(async (resolve, reject) => {
		const moveFile = ({
			fs,
			url,
			target,
			name
		}) => {
			return new Promise((resolve, reject) => {
				plus.io.resolveLocalFileSystemURL(url, res1 => {
					fs.root.getDirectory(target, {create: true}, fileEntry => {
						 res1.moveTo(fileEntry, name)
						resolve()
					}, reject)
				}, reject)
			})
		}
		
		const getFile = (url) => {
			return new Promise((resolve, rejcet) => {
				plus.io.resolveLocalFileSystemURL(url, resolve, (err) => {
					resolve(false)
				})
			})
		}
		const success = async (fs) => {
			try{
			const w = ''//await getFile(path + 'webview.js')
			if (!w) {
				console.log('没有webview.js 正在创建')
				const webviewJS = await downloadFile(
					'https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js')
				const res = await moveFile({
					fs,
					url: webviewJS.tempFilePath,
					target: path,
					name: 'uni.webview.1.5.2.js'
				})
				console.log('webview.js 创建完成'); 
			}
			const p = ''//await getFile(path + 'painter.js')
			if (!p) {
				console.log('没有painter.js 正在创建')
				fs.root.getFile(path + 'painter.js', {
					create: true
				}, fileEntry => {
					fileEntry.createWriter(async writer => {
						writer.onwrite  = () => {
							resolve(true)
							console.log('painter 创建完成'); 
						}
						writer.write(painterStr.replace(/\n/g, '\\n').replace(/\\/g, '\\'))
					})
				})
				console.log('painter.js 创建完成'); 
			}
		
			const h = '' //await getFile(path + 'index.html') //
			if (!h) {
				console.log('没有painter.html 正在创建')
				fs.root.getFile(path + 'index.html', {
					create: true
				}, fileEntry => {
					fileEntry.createWriter(writer => {
						writer.write(htmlStr)
						resolve(true)
						console.log('painter.html 创建完成'); 
					})
				})
			} else {
				resolve(true)
			}
			}catch(e){
				console.log(e)
			}
		}
		const error = (err) => {
			console.error(err)
		}
		plus.io.requestFileSystem(plus.io.PRIVATE_DOC, success, error)
	})
} 